package cn.wzvtc.ch4controllerparam;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

@RestController
public class FileController {
    @PostMapping("/uploadfile")
    public String uploadfile(@RequestParam("file") MultipartFile file) {
        //判空
        if (file.isEmpty()) {
            return "上传失败,请选择文件";
        }
        //1.创建文件存放路径
        File path = new File(".");//项目当前的工作路径
        File upload = new File(path.getAbsolutePath(), "/upload/");//创建存放文件的upload文件夹
        if (!upload.exists())
            upload.mkdirs();//创建路径
        //2.设置文件名
        String fileName = file.getOriginalFilename();//得到上传文件的文件名(包括后缀)
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//得到后缀
        fileName = UUID.randomUUID() + suffixName;//生成服务器储存的文件名
        //3.配置存放的文件
        File dest = new File(upload.getPath() + "/" + fileName);
        //4.保存文件
        try {
            file.transferTo(dest);//保存文件
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    //多个文件上传
    @PostMapping("/uploadfiles")
    public String uploadfiles(@RequestParam("files") MultipartFile[] files) {
        String strTemp = "";
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue;
            }
            File path = new File(".");
            File upload = new File(path.getAbsolutePath(), "/upload/");
            if (!upload.exists())
                upload.mkdirs();

            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suffixName;
            File dest = new File(upload.getPath() + "/" + fileName);

            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            strTemp += file.getOriginalFilename() + "上传成功" + "";
        }
        return strTemp;
    }

    @GetMapping("/downloadfile")
    public String downloadfile(String fileName, HttpServletResponse response) {
        try {
            //对文件名称编码
            fileName = new String(fileName.trim().getBytes("iso8859-1"),"UTF-8");
            //1.读取文件，并转换为文件流
            File path = new File(".");
            File upload = new File(path.getAbsolutePath(), "/upload/");
            File file = new File(upload.getPath() + "/" + fileName);
            FileInputStream fis = new FileInputStream(file);//转成文件流
            //2.创建response输出对象流
            response.setContentType("application/force-download");
            //response.addHeader("Content-Type", "application/octet-stream");
            response.addHeader("Content-disposition", "attachment:fileName=" + URLEncoder.encode(fileName,"utf-8"));//下载的文件名
            OutputStream os = response.getOutputStream();//创建一个response对象输出流
            //3.文件流写入response对象流:文件流操作
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = fis.read(buf)) != -1) {
                os.write(buf, 0, len);
            }
            //4.文件流关闭
            fis.close();
            return "下载成功";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "下载失败";
    }
}
